package com.kejiguan.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kejiguan.ui.adapter.DisplayItemAdapter;
import com.kejiguan.ui.dialog.CommDialogUtil;
import com.kejiguan.ui.event.OnKeyOperationEvent;
import com.kejiguan.ui.event.RefreshNeStateEvent;
import com.kejiguan.ui.model.DisplayArea;
import com.kejiguan.ui.model.ExhibitionNeItem;
import com.kejiguan.ui.presenter.EasyShuttlePresenter;
import com.kejiguan.ui.response.TakeAllOffResponse;
import com.kejiguan.ui.response.TakeAllOnResponse;
import com.kejiguan.ui.util.CacheDataUtil;
import com.kejiguan.ui.util.CommonDate;
import com.victor.loading.rotate.RotateLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;


/**
 * Created by apple on 16/3/31.
 *
 * 一键开关机
 */
public class EasyShuttleFragment extends Fragment implements View.OnClickListener {

    private MainActivity mainActivity;
    private View rootView;
    private ImageView takeOnBtn, takeOffBtn;

    private View actionLayout, neContainer;
    private View bottomLayout;
    private View backBtn;
    private TextView runningCountView;
    private RotateLoading loadingBar;

    private RecyclerView neList;
    private DisplayItemAdapter adapter;
    private EasyShuttlePresenter mPresenter;

    private int actionType=-1;
    private long actionTime;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        EventBus.getDefault().register(this);
        mainActivity = (MainActivity) getActivity();
        mPresenter = new EasyShuttlePresenter();
        mPresenter.attach(getContext());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {

        if (rootView == null) {

            rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_easy_shuttle_layout, container, false);
            actionLayout = rootView.findViewById(R.id.action_layout);
            takeOnBtn = (ImageView) rootView.findViewById(R.id.take_on_btn);
            takeOffBtn = (ImageView) rootView.findViewById(R.id.take_off_btn);

            neContainer = rootView.findViewById(R.id.neitem_container);
            neList = (RecyclerView) rootView.findViewById(R.id.ne_list);

            GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
            neList.setLayoutManager(layoutManager);

            bottomLayout= rootView.findViewById(R.id.bottom_layout);
            backBtn = rootView.findViewById(R.id.back_btn);
            backBtn.setOnClickListener(this);
            runningCountView = (TextView) rootView.findViewById(R.id.running_count_view);
            loadingBar= (RotateLoading) rootView.findViewById(R.id.loading_bar);

            takeOnBtn.setOnClickListener(this);
            takeOffBtn.setOnClickListener(this);

        }

        return rootView;
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.take_off_btn:
                ((MainActivity)getContext()).closeSlidingMenu();
                CommDialogUtil.getInstance().show(getContext(),"要关闭所有展项吗?",EasyShuttleFragment.this,"关机","取消",0);
                break;
            case R.id.take_on_btn:
                ((MainActivity)getContext()).closeSlidingMenu();
                CommDialogUtil.getInstance().show(getContext(),"要开启所有展项吗?",EasyShuttleFragment.this,"开机","取消",1);
                break;
            case R.id.dialog_confirm_btn:
                takeOnBtn.setClickable(false);
                takeOffBtn.setClickable(false);
                CommDialogUtil.getInstance().dismiss();
                int tag= (int) v.getTag(R.id.recyclerview_item_position);
                actionType=tag;
                if (tag==1)
                {
                    mPresenter.takeAllOn(getContext());
                }else
                {
                    mPresenter.takeAllOff(getContext());
                }
                actionTime=System.currentTimeMillis();
                break;
            case R.id.dialog_cancel_btn:
                CommDialogUtil.getInstance().dismiss();
                break;
            case R.id.back_btn:
                neContainer.setVisibility(View.GONE);
                ((MainActivity)getContext()).hideStateLayout();
                actionLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.dialog_one_btn:
                CommDialogUtil.getInstance().dismissOne();
                break;
        }

    }

    /**
     * 一件开机
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TakeAllOnResponse response) {
        if ("0000".equals(response.getRetCode()))
        {
            actionLayout.setVisibility(View.GONE);
            backBtn.setVisibility(View.GONE);
            backBtn.setClickable(false);
            loadingBar.start();
            loadingBar.setVisibility(View.VISIBLE);
            runningCountView.setText("开机进度:"+CacheDataUtil.getInstance().getTotalRunningCount()+" / "+CacheDataUtil.getInstance().getTotalCount());
            neContainer.setVisibility(View.VISIBLE);
            ((MainActivity)getContext()).showStateLayout();
            Toast.makeText(getContext(),"开机消息发送成功",Toast.LENGTH_SHORT).show();
            EventBus.getDefault().post(new OnKeyOperationEvent(true));

        }else
        {
            CommDialogUtil.getInstance().showOne(getContext(),response.getRetInfo(),EasyShuttleFragment.this,"确定",0);
        }

        takeOnBtn.setClickable(true);
        takeOffBtn.setClickable(true);

    }

    /**
     * 一件关机
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TakeAllOffResponse response) {

        if ("0000".equals(response.getRetCode()))
        {
            actionLayout.setVisibility(View.GONE);
            backBtn.setVisibility(View.GONE);
            backBtn.setClickable(false);
            loadingBar.start();
            loadingBar.setVisibility(View.VISIBLE);
            runningCountView.setText("关机进度:"+CacheDataUtil.getInstance().getTotalexitCount()+" / "+CacheDataUtil.getInstance().getTotalCount());
            neContainer.setVisibility(View.VISIBLE);
            ((MainActivity)getContext()).showStateLayout();
            Toast.makeText(getContext(),"关机消息发送成功",Toast.LENGTH_SHORT).show();
            EventBus.getDefault().post(new OnKeyOperationEvent(false));

        }else
        {
            CommDialogUtil.getInstance().showOne(getContext(),response.getRetInfo(),EasyShuttleFragment.this,"确定",0);
        }

        takeOnBtn.setClickable(true);
        takeOffBtn.setClickable(true);
    }
    /**
     * 定时刷新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshNeStateEvent event) {

        if (actionType!=-1)
        {
            if (actionType==0)
            {

                //关闭
                runningCountView.setText("关机进度:"+CacheDataUtil.getInstance().getTotalexitCount()+" / "+CacheDataUtil.getInstance().getTotalCount());

                if (CacheDataUtil.getInstance().getTotalexitCount()==CacheDataUtil.getInstance().getTotalCount()&&CacheDataUtil.getInstance().getTotalCount()!=0)
                {
                    backBtn.setVisibility(View.VISIBLE);
                    backBtn.setClickable(true);
                    loadingBar.stop();
                    loadingBar.setVisibility(View.GONE);
                }else
                {
                    backBtn.setVisibility(View.INVISIBLE);
                }

            }else
            {
                //开启操作

                runningCountView.setText("开机进度:"+CacheDataUtil.getInstance().getTotalRunningCount()+" / "+CacheDataUtil.getInstance().getTotalCount());

                if (CacheDataUtil.getInstance().getTotalRunningCount()==CacheDataUtil.getInstance().getTotalCount()&&CacheDataUtil.getInstance().getTotalCount()!=0)
                {
                    backBtn.setVisibility(View.VISIBLE);
                    backBtn.setClickable(true);
                    loadingBar.stop();
                    loadingBar.setVisibility(View.GONE);
                }else
                {
                    backBtn.setVisibility(View.INVISIBLE);
                }

            }

            List<DisplayArea> displayAreas = CacheDataUtil.getInstance().getDisplayAreas();
            List<ExhibitionNeItem> exhibitionNeItems = new ArrayList<>();
            for (DisplayArea displayArea : displayAreas) {
                if (displayArea.getExhibitionNeItems() != null) {
                    exhibitionNeItems.addAll(displayArea.getExhibitionNeItems());
                }
            }

            if (null == adapter) {
                adapter = new DisplayItemAdapter(getContext(), exhibitionNeItems);
                neList.setAdapter(adapter);
            } else {
                adapter.setPresenterItems(exhibitionNeItems);
            }

            boolean isAllRunnning=true;
            boolean isAllClosed=true;
            for (ExhibitionNeItem exhibitionNeItem:exhibitionNeItems)
            {
                if (!exhibitionNeItem.getExhibitionState().equals(CommonDate.STATE_RUNNING))
                {
                    isAllRunnning=false;
                    break;
                }
            }

            for (ExhibitionNeItem exhibitionNeItem:exhibitionNeItems)
            {
                if (!exhibitionNeItem.getExhibitionState().equals(CommonDate.STATE_EXIT))
                {
                    isAllClosed=false;
                    break;
                }
            }

            if (isAllRunnning)
            {
                takeOnBtn.setClickable(false);
                takeOnBtn.setImageResource(R.mipmap.kjg_take_on_btn_big_bt2);
            }else
            {
                takeOnBtn.setClickable(true);
                takeOnBtn.setImageResource(R.mipmap.kjg_take_on_btn_big_bt1);
            }

            if (isAllClosed)
            {
                takeOffBtn.setClickable(false);
                takeOffBtn.setImageResource(R.mipmap.kjg_take_off_btn_big_bt2);
            }else
            {
                takeOffBtn.setClickable(true);
                takeOffBtn.setImageResource(R.mipmap.kjg_take_off_btn_big_bt1);
            }

            if ((System.currentTimeMillis()-actionTime)>=2*60*1000)
            {
                backBtn.setVisibility(View.VISIBLE);
                backBtn.setClickable(true);
            }



        }
    }

    public boolean shouldShowStateLayout()
    {
        if (neContainer!=null&&neContainer.getVisibility()==View.VISIBLE)
        {
            return true;
        }else
        {
            return false;
        }
    }


}
